﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data;

namespace Utility
{
    public class LinqTransaction<TDatabase> where TDatabase : DataContext
    {
        public LinqTransaction(TDatabase tDatabase, bool isLock)
        {
            try
            {
                this.tDatabase = tDatabase;
                OpenConnection();
                this.tDatabase.Transaction = isLock
                                                 ? tDatabase.Connection.BeginTransaction(IsolationLevel.ReadCommitted)
                                                 : tDatabase.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
            }
            catch (Exception ex)
            {
                //throw new Log.HSException(Log.HSLogLevel.Error, Common.Constants.Messages.HS_MSG_DB_CONNECTION_ERR, ex.TargetSite.ToString(), ex.StackTrace);
                //datbh Edit 24/12/2008
                //throw new Log.HSException(ex, Common.Constants.Messages.HS_MSG_DB_CONNECTION_ERR);
            }
        }
        private readonly TDatabase tDatabase;


        private void OpenConnection()
        {
            if (tDatabase.Connection.State == ConnectionState.Closed)
            {
                tDatabase.Connection.Open();
            }
        }
        private void CloseConnection()
        {
            if (tDatabase.Connection.State == ConnectionState.Open)
            {
                tDatabase.Connection.Close();
            }
        }
        private void Rollback()
        {
            if (tDatabase.Transaction != null)
                tDatabase.Transaction.Rollback();
        }
        private void Dispose()
        {
            if (tDatabase.Transaction == null) return;
            tDatabase.Transaction.Dispose();
            tDatabase.Transaction = null;
        }


        /// <summary>
        /// Commite and dispose transaction.
        /// </summary>
        public void CommitAndDispose()
        {
            try
            {
                tDatabase.Transaction.Commit();
            }
            catch
            {
                Rollback();
                throw;
            }
            finally
            {
                CloseConnection();
                Dispose();
            }
        }

        /// <summary>
        /// Rollback and dispose transaction.
        /// </summary>
        public void RollbackAndDispose()
        {
            Rollback();
            CloseConnection();
            Dispose();
        }


        //---------------------------------------------------------------------------------------

    }

}

